import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

import { UrlManager } from '@shared/url/url.manager';
import { HttpServer, HeaderParam } from '@core/net/http-server';
import { TokenService } from '@core/auth/token/token.service';

import { Validate } from '../model/Validate';

@Injectable()
export class PassportService {

  constructor(
    private http: HttpServer,
    private tokenService: TokenService
  ) { }

  private _redirectUrl: string;

  get redirectUrl() {
    return this._redirectUrl;
  }

  set redirectUrl(val: string) {
    this._redirectUrl = val;
  }

  login(account: string, password: string, verify: string, verifyToken: string): Observable<boolean> {
    const headerParam: Array<HeaderParam> = [{
      key: 'Content-Type',
      value: 'application/json'
    }, {
      key: 'Authorization',
      value: verifyToken
    }];
    return this.http.post(UrlManager.user.userLoginUrl, {
      account: account,
      password: password,
      verify: verify
    }, headerParam, false)
      .pipe(
        mergeMap((event: any) => {
          this.tokenService.set({
            token: event
          });
          return of(this.tokenService.get() ? true : false);
        })
      );
  }

  verify(): Observable<Validate> {
    return this.http.get<Validate>(UrlManager.user.verifyUrl, {
      time: new Date().getTime()
    });
  }
}
